package com.momo.encoderHandler3;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;
import java.util.UUID;

/**
 * @author Kagome
 * @title: MyServerHandler
 * @projectName boot2.X-netty
 * @description: 入站处理器
 * @date 2019/6/2 16:15
 */
public class MyServerHandler extends SimpleChannelInboundHandler<PersionProtocol>{

    private int count=0;
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, PersionProtocol msg) throws Exception {
        int length=msg.getLength();
        byte[] content=msg.getContent();
        System.out.println("服务器接收到的数据:");
        System.out.println("长度:"+length);
        System.out.println("内容:"+new String(content, Charset.forName("utf-8")));
        System.out.println("执行次数"+(++count));
        String uuid= UUID.randomUUID().toString();
        int responseLength=uuid.getBytes("utf-8").length;
        byte[] responseContent=uuid.getBytes("utf-8");
        PersionProtocol persionProtocol=new PersionProtocol();
        persionProtocol.setContent(responseContent);
        persionProtocol.setLength(responseLength);
        ctx.writeAndFlush(persionProtocol);

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
